<template>
  <div class="wrapper">
    <el-form :inline="true">
      <el-form-item>
        <!-- <el-select v-model="deptId"
          placeholder="请选择部门"
          @change="_reset">
          <el-option v-for="item in depts"
            :key="item.id"
            :value="item.id"
            :label="item.name"></el-option>
        </el-select> -->
         <el-cascader :options="depts"
            :props="{ value: 'id', label: 'name', children: 'downDept' }"
            v-model="deptId"
            :show-all-levels="false"
            change-on-select
            clearable
            @change="_reset">
          </el-cascader>
      </el-form-item>
      <el-form-item>
        <el-input placeholder="请输入绩效目标名称"
          v-model="search"
          clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
          @click.native="_reset"
          size="small"
          style="width:60px">
          <i class="el-icon-search"></i>
        </el-button>
      </el-form-item>
      <el-form-item class="fr"
        v-has="'achievementredact'">
        <el-button type="primary"
          size="small"
          style="width:60px"
          @click="add">
          新增
        </el-button>
      </el-form-item>
    </el-form>
    <el-form>
      <el-form-item>
        <el-table :data="formulateList"
          max-height="550">
          <el-table-column fixed
            prop="id"
            label="编号"
            width="100">
          </el-table-column>
          <el-table-column label="绩效目标名称"
            prop="name"
            fixed
            width="100">
          </el-table-column>
          <el-table-column label="目标有效期"
            prop="timeLimit"
            width="200">
          </el-table-column>
          <el-table-column label="拉新量"
            prop="newNum"
            width="100">
          </el-table-column>
          <el-table-column label="订单目标"
            prop="orderTarget"
            width="100">
          </el-table-column>
          <el-table-column label="员工拉新奖励"
            prop="pullStaffAward"
            width="100">
          </el-table-column>
          <el-table-column label="员工订单奖励"
            prop="staffOrder"
            width="100">
          </el-table-column>
          <el-table-column label="负责人拉新奖励"
            prop="pullLeaderAward"
            width="150">
          </el-table-column>
          <el-table-column label="负责人订单奖励"
            prop="leaderOrder"
            width="150">
          </el-table-column>
          <el-table-column label="适用部门"
            prop="deptName"
            width="100">
          </el-table-column>

          <el-table-column label="创建人"
            prop="createUser"
            width="100">
          </el-table-column>
          <el-table-column label="创建时间"
            prop="createTime"
            width="100">
          </el-table-column>
          <el-table-column label="最后修改人"
            prop="upUser"
            width="100">
          </el-table-column>
          <el-table-column label="修改时间"
            prop="upTime"
            width="100">
          </el-table-column>
          <el-table-column label="状态"
            width="100">
            <template slot-scope="scope">
              <!-- 1：未开始，2：进行中，3：已结束 -->
              <span v-if="scope.row.state ==1">未开始</span>
              <span v-if="scope.row.state ==2">进行中</span>
              <span v-if="scope.row.state ==3">已结束</span>
              
            </template>
          </el-table-column>
          <el-table-column label="操作"
            v-has="'achievementredact'"
            width="200"
            fixed="right">
            <template slot-scope="scope">
              <el-button type="text"
                @click="look(scope.row.id)">查看</el-button>
              <el-button type="text" v-if="scope.row.state==1"
                @click="edit(scope.row.id)">编辑</el-button>
              <el-button type="text"
                v-if="scope.row.state ==2"
                @click="updateState(scope.row)">结束</el-button>
               <el-button type="text"
                 v-if="scope.row.state!=2"
                @click="updateState(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item class="fr">
        <el-pagination @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, prev , pager , next, sizes"
          :total="total"
          style="margin-top:20px">
        </el-pagination>
      </el-form-item>

    </el-form>
    <!-- 新增编辑弹窗 -->
    <el-dialog :title="title"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      height="200"
      class="dialog"
      width="800px">
      <el-form label-width="120px"
        :disabled="isLook"
        ref="formData"
        :rules="rules"
        :model="targetInfo">
        <el-form-item label="绩效目标名称："
          prop="name">
          <el-input placeholder="请选择绩效目标名称"
            v-model="targetInfo.name"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="适用部门："
          prop="dept">
          <el-cascader :options="depts"
            :props="{ value: 'id', label: 'name', children: 'downDept' }"
            v-model="targetInfo.dept"
            :show-all-levels="false"
            change-on-select
            @change="deptChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="无需要考核人员："
          v-if="targetInfo.dept"
          style="margin-bottom:0px">
          <div>
            <el-checkbox v-for="item in deptStaff"
              @change="checkboxChange"
              v-model="item.check"
              :key="item.id">{{item.name}}</el-checkbox>
          </div>
        </el-form-item>
        <el-form-item label="部门营销负责人："
          v-show="leader"
          style="margin-bottom:0px">
          <span style="font-size:12px">{{leader}}</span>
        </el-form-item>
        <el-form-item label="完成目标时间："
          required>
          <el-radio :label="1"
            v-model="targetInfo.timeType">每月目标</el-radio>
          <el-radio v-model="targetInfo.timeType"
            :label="2">自定义时间</el-radio>
          <el-form-item prop="startEndTime"
            style="display:inline-block;"
            v-if="targetInfo.timeType == 2">
            <el-date-picker v-model="startEndTime"
              type="daterange"
              size="small"
              @change="startEndTimeChange"
              style="height:34px;margin-left:30px"
              range-separator="至"
              start-placeholder="开始日期"
              value-format="yyyy-MM-dd"
              :clearable="false"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

        </el-form-item>
        <h1 class="title">目标要求</h1>
        <el-form-item style="margin-bottom:0px">
          <el-radio :label="1"
            v-model="targetInfo.type">按部门</el-radio>
          <el-radio v-model="targetInfo.type"
            :label="2">按个人</el-radio>
        </el-form-item>
        <el-form-item label="拉新量："
          prop="newQuantity">
          <el-input-number controls-position="right"
            :min="1"
            :max="10000"
            
            v-model="targetInfo.newQuantity"
            :precision="0"
            size="small"></el-input-number>&nbsp;&nbsp;
          <span>位</span>
          <label class="notice"
            v-if="targetInfo.type ==1&&targetInfo.newQuantity && countPerson">&nbsp;&nbsp;&nbsp;&nbsp;部门考核人员目标拉新{{Math.ceil((targetInfo.newQuantity)/countPerson)}}人</label>
          <label class="notice"
            v-if="targetInfo.type ==2&&targetInfo.newQuantity && countPerson">&nbsp;&nbsp;&nbsp;&nbsp;部门总目标拉新{{targetInfo.newQuantity*countPerson}}人</label>
        </el-form-item>
        <el-form-item style="margin-bottom:0px">
          <el-radio label="1"
            v-model="targetInfo.orderType">订单数</el-radio>
          <el-radio label="2"
            v-model="targetInfo.orderType">订单额</el-radio>
        </el-form-item>
        <el-form-item label="订单数："
          prop="orderNumber"
          v-if="targetInfo.orderType == 1">
          <el-input-number controls-position="right"
            :min="1"
            :max="20000"
            :precision="0"
            v-model="targetInfo.orderNumber"
            size="small"></el-input-number>&nbsp;&nbsp;
          <span>单</span>
          <label class="notice"
            v-if="targetInfo.orderNumber && targetInfo.type ==1 && countPerson">&nbsp;&nbsp;&nbsp;&nbsp;部门考核人员目标产生订单数{{Math.ceil(targetInfo.orderNumber/countPerson)}}单</label>
          <label class="notice"
            v-if="targetInfo.orderNumber && targetInfo.type ==2 && countPerson">&nbsp;&nbsp;&nbsp;&nbsp;部门总目标产生订单{{targetInfo.orderNumber*countPerson}}单</label>
        </el-form-item>
        <el-form-item label="订单额："
          v-if="targetInfo.orderType == 2"
          prop="orderType">
          <el-input-number controls-position="right"
            :min="0"
            :max="10000000"
            :precision="2"
            v-model="targetInfo.orderAmount"
            size="small"></el-input-number>&nbsp;&nbsp;
          <span>元</span>
          <label class="notice"
            v-if="targetInfo.orderAmount && targetInfo.type ==1&& countPerson">&nbsp;&nbsp;&nbsp;&nbsp;部门考核人员目标产生订单{{Math.ceil(targetInfo.orderAmount/countPerson)}}元</label>
          <label class="notice"
            v-if="targetInfo.orderAmount && targetInfo.type ==2&& countPerson">&nbsp;&nbsp;&nbsp;&nbsp;部门总目标产生订单{{targetInfo.orderAmount*countPerson}}元</label>
        </el-form-item>

        <h1 class="title">奖励规则设置</h1>
        <p class="second-title">拉新目标完成奖励：</p>
        <div class="clearfix">
          <el-form-item label="负责人："
            prop="completeResponsible"
            class="fl">
            <el-input-number controls-position="right"
              :min="0"
              :max="10000"
              :precision="2"
              v-model="targetInfo.completeResponsible"
              size="small"></el-input-number>&nbsp;&nbsp;
            <span>元/位</span>
          </el-form-item>
          <el-form-item label="考核人员："
            prop="completeMember"
            class="fl">
            <el-input-number controls-position="right"
              :min="0"
              v-model="targetInfo.completeMember"
              :max="10000"
              :precision="2"
              size="small"></el-input-number>&nbsp;&nbsp;
            <span>元/位</span>
          </el-form-item>
        </div>
        <p class="second-title">拉新目标未完成奖励：</p>
        <div class="clearfix">
          <el-form-item label="负责人："
            prop="unfinishedResponsible"
            class="fl">
            <el-input-number controls-position="right"
              :min="0"
              :max="10000"
              :precision="2"
              v-model="targetInfo.unfinishedResponsible"
              size="small"></el-input-number>&nbsp;&nbsp;
            <span>元/位</span>
          </el-form-item>
          <el-form-item label="考核人员："
            prop="unfinishedMember"
            class="fl">
            <el-input-number controls-position="right"
              :min="0"
              :max="1000"
              :precision="2"
              v-model="targetInfo.unfinishedMember"
              size="small"></el-input-number>&nbsp;&nbsp;
            <span>元/位</span>
          </el-form-item>
        </div>
        <div v-if="targetInfo.orderType == 1">
          <p class="second-title">订单目标完成奖励：（未完成目标不额外奖励，完成目标按有效订单数量设置）</p>
          <div class="clearfix">
            <el-form-item label="负责人："
              prop="orderResponsible"
              class="fl">
              <el-input-number controls-position="right"
                :min="0"
                :max="10000"
                :precision="2"
                v-model="targetInfo.orderResponsible"
                size="small"></el-input-number>&nbsp;&nbsp;
              <span>元/单</span>
            </el-form-item>
            <el-form-item label="考核人员："
              prop="orderMember"
              class="fl">
              <el-input-number controls-position="right"
                :min="0"
                :max="10000"
                :precision="2"
                v-model="targetInfo.orderMember"
                size="small"></el-input-number>&nbsp;&nbsp;
              <span>元/单</span>
            </el-form-item>
          </div>
          <label class="notice"
            v-if="targetInfo.orderResponsible&& targetInfo.orderMember"
            style="padding-left:30px;">推荐注册人每成交一个订单，奖励{{targetInfo.orderResponsible+targetInfo.orderMember}}元</label>
        </div>
        <div v-if="targetInfo.orderType == 2">
          <p class="second-title">订单目标完成奖励：（未完成目标不额外奖励，完成目标按订单金额比例设置）</p>
          <div class="clearfix">
            <el-form-item label="负责人："
              prop="orderResponsible"
              class="fl">
              <el-input-number controls-position="right"
                :min="0"
                :max="100"
                :precision="2"
                v-model="targetInfo.orderResponsible"
                size="small"></el-input-number>&nbsp;&nbsp;
              <span>%</span>
            </el-form-item>
            <el-form-item label="考核人员："
              prop="orderMember"
              class="fl">
              <el-input-number controls-position="right"
                :min="0"
                :max="100"
                :precision="2"
                v-model="targetInfo.orderMember"
                size="small"></el-input-number>&nbsp;&nbsp;
              <span>%</span>
            </el-form-item>
          </div>
          <label class="notice"
            style="padding-left:30px;">设置会员分享营销奖励比例为5%，推荐注册人每成交订单（如：成交订单金额为500元），奖励发放500*5%=25元</label>
        </div>
      </el-form>
      <span slot="footer"
        style="text-align:center"
        class="dialog-footer">
        <span v-if="!isLook">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary"
            @click="sure('formData')">确 定</el-button>
        </span>
        <span v-if="isLook">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getFormulateList,
  getPullDeptList,
  getInfo,
  getMember,
  updateAchievement,
  setState
} from "@/public/js/performance";
export default {
  components: {},
  props: {},
  data() {
    return {
      stateStr: "全部状态",
      pageNum: 1,
      pageSize: 10,
      total: 0,
      isLook: true,
      deptId: [],
      depts: [],
      search: "",
      id: "",
      countPerson: 0, //考核人数
      leader: "",
      startEndTime: [],
      targetInfo: {},
      formulateList: [],
      deptStaff: [],
      deptStaffChecked: [],
      title: "新增绩效目标",
      dialogVisible: false,
      storeDeptId: "",
      rules: {
        name: [
          { required: true, message: "请输入绩效目标名称", trigger: "blur" }
        ],
        dept: [{ required: true, message: "请选择部门", trigger: "change" }],
        newQuantity: [
          { required: true, message: "请输入拉新量", trigger: "blur" }
        ],
        orderNumber: [
          { required: true, message: "请输入订单数", trigger: "blur" }
        ],
        orderAmount: [
          { required: true, message: "请输入订单额", trigger: "blur" }
        ],
        startEndTime: [
          {
            type: "array",
            required: true,
            message: "请选择自定义时间",
            trigger: "change"
          }
        ],
        completeResponsible: [
          { required: true, message: "请输入负责人奖励金额", trigger: "blur" }
        ],
        completeMember: [
          { required: true, message: "请输入成员奖励金额", trigger: "blur" }
        ],
        unfinishedResponsible: [
          { required: true, message: "请输入未完成负责人金额", trigger: "blur" }
        ],
        unfinishedMember: [
          { required: true, message: "请输入未完成成员奖励", trigger: "blur" }
        ],
        orderResponsible: [
          {
            required: true,
            message: "请输入订单负责人完成奖励",
            trigger: "blur"
          }
        ],
        orderMember: [
          { required: true, message: "请输入订单员工奖励", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    deptStaff: {
      handler(newCount) {
        this.countPerson = newCount.filter(item => item.check == false).length;
      },
      deep: true
    }
  },
  computed: {},
  methods: {
    // 获取列表数据
    _getFormulateList() {
      getFormulateList({
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        deptId: this.deptId.length ? this.deptId[this.deptId.length-1] : '',
        search: this.search
      }).then(res => {
        this.formulateList = res.data.formulateList;
        this.total = res.data.total;
      });
    },
    checkboxChange() {
      console.log(this.deptStaff);
    },
    //修改为结束状态
    updateState(data) {
      let {state,id} = data;
      //进行中
     if(state==2) {
       state =3
     } else if (state !==2) {
       state =4
     }
      this.$confirm("是否继续此操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        setState({
          targetId: id,
          state: state
        }).then(res => {
          if (!res.data.errCode) {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this._getFormulateList();
          }
        });
      });
    },
    startEndTimeChange(time) {
      this.targetInfo.startEndTime = time;
    },
    // 获取部门下拉数据
    _getPullDeptList() {
      getPullDeptList({
        id: ""
      }).then(res => {
        this.depts = res.data.depts;
        console.log("this.depts", this.depts);
      });
    },
    _reset() {
      this.pageNum = 1;
      this.pageSize = 10;
      this._getFormulateList();
    },
    edit(id) {
      this.id = id;
      this.isLook = false;
      this.dialogVisible = true;
      this.title="编辑绩效目标"
      this._getInfo();
    },
    look(id) {
      this.id = id;
      this.isLook = true;
      this.dialogVisible = true;
      this._getInfo();
    },
    add() {
      this.id = "";
      this.isLook = false;
      this.targetInfo.startEndTime = [];
      this.deptStaff = [];
      this.leader = "";
      this.targetInfo = {
        timeType: 1,
        orderType: "1",
        type: 1
      };
      this.dialogVisible = true;
    },
    sure(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let data = {
            id: this.id,
            name: this.targetInfo.name,
            deptId: this.targetInfo.dept[this.targetInfo.dept.length - 1],
            userId: this.deptStaff,
            timeType: this.targetInfo.timeType,
            startTime:
              this.targetInfo.timeType == 2
                ? this.targetInfo.startEndTime[0]
                : "",
            endTime:
              this.targetInfo.timeType == 2
                ? this.targetInfo.startEndTime[1]
                : "",
            type: this.targetInfo.type,
            pullNewNum: this.targetInfo.newQuantity,
            orderType: this.targetInfo.orderType,
            orderMoney:
              this.targetInfo.orderType == 2 ? this.targetInfo.orderAmount : "",
            orderNum:
              this.targetInfo.orderType == 1 ? this.targetInfo.orderNumber : "",
            loseMoeny: this.targetInfo.unfinishedResponsible,
            winMoeny: this.targetInfo.completeResponsible,
            winStaffMoeny: this.targetInfo.completeMember,
            loseStaffMoeny: this.targetInfo.unfinishedMember,
            orderWinMoeny: this.targetInfo.orderResponsible,
            orderWinStaffMoeny: this.targetInfo.orderMember
          };
          console.log("data", data);

          updateAchievement(data).then(res => {
            if (!res.data.errCode) {
              this.$message({
                message: this.id ? "修改成功" : "新增成功",
                type: "success"
              });
              this.dialogVisible = false;
              this._getFormulateList();
            }
          });
        } else {
          return false;
        }
      });
    },
    deptChange(deptArray) {
      this.storeDeptId = deptArray[deptArray.length - 1];
      this.depts.forEach(item => {
        if (item.id == this.storeDeptId) {
          this.leader = item.leader;
        }
      });
      this._getMember();
    },
    _getMember() {
      this.deptStaffChecked = [];
      getMember({
        targetId: this.id,
        deptId: this.storeDeptId
      }).then(res => {
        this.deptStaff = res.data.deptStaff;
      });
    },
    _getInfo() {
      getInfo({
        id: this.id
      }).then(res => {
        this.targetInfo = res.data.targetInfo;
        this.targetInfo.startEndTime = this.startEndTime = [
          this.targetInfo.startTime,
          this.targetInfo.endTime
        ];
        this.storeDeptId = this.targetInfo.dept;
        this.targetInfo.dept = this.targetInfo.depts;
        this.depts.forEach(item => {
          if (item.id == this.storeDeptId) {
            this.leader = item.leader;
          }
        });
        this._getMember(this.storeDeptId);
      });
    },
    //分页
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this._getFormulateList();
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this._getFormulateList();
    }
  },
  created() {
    this._getFormulateList();
    this._getPullDeptList();
  },
  mounted() {}
};
</script>
<style lang="scss" scoped>
.wrapper {
  font-size: 12px;
  .el-input {
    width: 200px;
  }
  .dialog {
    .title {
      color: #6d2377;
      display: inline;
      font-size: 16px;
      padding-right: 36px;
    }
    .el-form-item {
      margin-bottom: 15px;
    }
    .second-title {
      padding: 10px 0 10px 30px;
    }
    .notice {
      font-size: 12px;
      color: #999;
    }
    .el-checkbox {
      margin: 0;
      margin-right: 15px;
    }
  }
}
</style>